require(['common', 'request'], function (common, Request) {
    $(function () {
        var __password_win = {
            formId: 'formUserPassword',
            validObj: "",
            init: function () {
                this.validObj = common.initValidForm($('#' + this.formId));
                var req = new Request('api/current/user/info');
                req.get({
                    isErrorTip: false,
                    success: function (data) {
                        $('#userId').val(data['userId']);
                    }
                });
            },
            validate: function () {
                var newPwd = $('#newPassword').val();
                var confirmPwd = $('#confirmPassword').val();
                if (!this.validObj.check()) {
                    common.errorMsg('验证不通过，请根据错误信息修改。');
                    return false;
                }
                if (newPwd !== confirmPwd) {
                    common.errorMsg('两次输入密码不一致，请确认后再提交。')
                    return false;
                }
                return true;
            },
            getData: function(){
                var userId = $('#userId').val();
                var oldPwd = $('#oldPassword').val();
                var newPwd = $('#newPassword').val();
                var confirmPwd = $('#confirmPassword').val();
                var params = {
                    id: userId,
                    oldPwd: oldPwd,
                    newPwd: newPwd,
                    confirmPwd: confirmPwd
                };
                return params;
            },
            postData: function (beforeFn, afterFn) {
                var that = this;
                if(this.validate()) {
                    beforeFn && beforeFn();
                    var p = that.getData();
                    var req = new Request('api/sys/user/password');
                    req.ajax({
                        type: 'POST',
                        data: p,
                        success: function (data) {
                            afterFn(data);
                        },
                        error: function(xhr) {
                            var msg = "";
                            if (xhr && xhr.responseJSON && xhr.responseJSON.msg) {
                                msg = xhr.responseJSON.msg;
                                common.errorMsg(msg);
                            } else {
                                msg = "请求接口异常，稍后尝试！";
                            }
                            afterFn({code: "100", msg: msg});
                        }
                    })
                }
            }
        };
        __password_win.init();
        window.__password_win = __password_win;
    })
});